import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
  ScopeContext,
} from '@fast-crud/fast-crud';

import type { FormRulesExt } from '#/api';
import type { ExtendInterfaceLoggingModel } from '#/api/basic/msg/model/extendInterfaceLoggingModel';
import type { ActionEnum } from '#/enums/commonEnum';

import { h, ref } from 'vue';
import { Codemirror } from 'vue-codemirror';

import { useAccess } from '@vben/access';
import { JsonViewer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { java } from '@codemirror/lang-java';
import { oneDark } from '@codemirror/theme-one-dark';

import { ExtendInterfaceLoggingApi } from '#/api/basic/msg/extendInterfaceLogging';
import { DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
} from '#/plugins/fast-crud/common';

const logExtensions = [java(), oneDark];
const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.ops.defInterfaceLog;
export function createCrudOptions(
  props: CreateCrudOptionsProps<
    ExtendInterfaceLoggingModel.ExtendInterfaceLoggingResultVO,
    any
  >,
): CreateCrudOptionsRet<ExtendInterfaceLoggingModel.ExtendInterfaceLoggingResultVO> {
  const selectedRowKeys = ref<string[]>([]);

  return {
    crudOptions: {
      request: {
        pageRequest: ExtendInterfaceLoggingApi.pageRequest,
        addRequest: ExtendInterfaceLoggingApi.addRequest,
        editRequest: ExtendInterfaceLoggingApi.editRequest,
        delRequest: ExtendInterfaceLoggingApi.delRequest,
        infoRequest: ExtendInterfaceLoggingApi.infoRequest,
      },
      form: {
        col: { span: 24 },
        wrapper: { is: 'a-drawer', draggable: false, size: '50%' },
      },
      actionbar: {
        buttons: {
          add: { show: false },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            role: permCode.loggingDelete,
            removeFn: ExtendInterfaceLoggingApi.remove,
          }),
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '200px',
        buttons: {
          edit: { show: false },
          view: { show: true },
          remove: {
            show: hasPermission(permCode.loggingDelete),
          },
          copy: { show: false },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        execTime: {
          title: $t('basic.msg.extendInterfaceLogging.execTime'),
          type: 'datetime',
          form: {
            component: {
              vModel: 'formatted-value',
              defaultTime: '00:00:00',
              format: 'yyyy-MM-dd HH:mm:ss',
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null && row) {
              row[key] = value;
            }
          },
          viewForm: {
            render: ({ value }: ScopeContext) => {
              return <span>{value}</span>;
            },
          },
          column: {
            show: true,
          },
        },
        status: {
          title: $t('basic.msg.extendInterfaceLogging.status'),
          type: 'dict-select',
          dict: backendDict(DictEnum.MsgInterfaceLoggingStatusEnum),
          column: { width: 100 },
          search: { show: true },
        },
        params: {
          title: $t('basic.msg.extendInterfaceLogging.params'),
          type: ['text', 'copyable'],
          viewForm: { ignoreUseCellComponent: true },
          form: {
            render: (scope: ScopeContext) => {
              try {
                const json = JSON.parse(scope.form.params);
                if (json) {
                  return (
                    <JsonViewer boxed copyable expand-depth="3" value={json} />
                  );
                }
                return h('div', scope.form.params);
              } catch {
                return h('div', scope.form.params);
              }
            },
          },
        },
        result: {
          title: $t('basic.msg.extendInterfaceLogging.result'),
          type: ['text', 'copyable'],
          viewForm: { ignoreUseCellComponent: true },
          form: {
            render: (scope: ScopeContext) => {
              try {
                const json = JSON.parse(scope.form.result);
                if (json) {
                  return (
                    <JsonViewer boxed copyable expand-depth="3" value={json} />
                  );
                }
                return h('div', scope.form.result);
              } catch {
                return h('div', scope.form.result);
              }
            },
          },
          column: { show: false },
        },
        errorMsg: {
          title: $t('basic.msg.extendInterfaceLogging.errorMsg'),
          type: ['text', 'copyable'],
          viewForm: {
            ignoreUseCellComponent: true,
            render: (scope: ScopeContext) => {
              return h(Codemirror, {
                autofocus: true,
                extensions: logExtensions,
                indentWithTab: true,
                style: { height: '200px' },
                tabSize: 2,
                modelValue: scope.form.errorMsg,
              });
            },
          },
          column: { show: false },
        },
        bizId: {
          title: $t('basic.msg.extendInterfaceLogging.bizId'),
          type: 'text',
          column: { show: false },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
